<template>
  <div>
    <!-- 下拉框 -->
    <div style="width: 100%" v-if="props.selectType==SelectTypeEnum.tSelect">
        <t-select v-model="props.value" :placeholder='props.placeholder' @change="changeDict">
          <t-option
            v-for="(item, _) in groupSelectOptions"
            :key="item.dictValue"
            :value="numReg.test(item.dictValue)?Number(item.dictValue):item.dictValue"
            :label="$t(item.dictLabel)"
          />
        </t-select>
    </div>
    <!-- 横巷选择框 -->
    <div v-if="props.selectType==SelectTypeEnum.tRadio">
        <t-radio-group :default-value="props.value.toString()" @change="changeDict">
          <t-radio-button v-for="(item,index) in groupSelectOptions" :key="index" :value="item.dictValue"
            >{{ $t(item.dictLabel) }}
          </t-radio-button>
        </t-radio-group>
    </div>
  </div>
  </template>

  <script setup lang="ts">
  import {onBeforeMount, ref} from 'vue';
  import {DictData} from "@/api/system/dict/types";
  import {useDictStore} from "@/store";
  import {  SelectTypeEnum } from './types';

  const numReg = new RegExp(/^[0-9]*$/)

  const dictStore = useDictStore();

  /**
   * 字典数据存储
   */
  const groupSelectOptions = ref<DictData[]>();

  /**
   * props 组件支持参数
   * @param dictType 字典类型
   * @param placeholder 缺省显示提示
   * @param value 双向绑定的字段
   * @param selectType 组件渲染类型
   * @param defaultValue 默认值
   */
  const props = withDefaults(defineProps<{
		dictType: string,
    placeholder?:string,
    value: string | number,
    selectType?: SelectTypeEnum,
    defaultValue?: string
	}>(),{
    selectType:SelectTypeEnum.tSelect,
	})

  /**
   * emit 事件
   */
  const emit = defineEmits(['onChange','update:value']);

  /**
   * 获取字典数据
   */
  const getSysDictType = async () => {
    const sysDictType = await dictStore.dictFunction(props.dictType);
    if (sysDictType) {
      groupSelectOptions.value = sysDictType;
      props.defaultValue=sysDictType[0].dictValue
    }
  };

  /**
   * 选择框值变化
   */
  const changeDict = (content: any) => {
    emit('onChange',content);
    emit('update:value',content);
  };

  onBeforeMount(async () => {
    await getSysDictType();
  });
  </script>
  <style lang="less" scoped>
    .t-radio-group{
      background: white !important;
    }
  </style>
